package mylist;

import java.util.Arrays;

public class MyArrayList implements IList{
    public int[] elem;
    public int usedSize;
    public static final int DEFAULT_SIZE=10;
    public MyArrayList(){
        this.elem=new int[DEFAULT_SIZE];
    }
    public MyArrayList(int capacity){
        this.elem=new int[capacity];
    }
    public void display(){
        for(int i=0;i<this.usedSize;i++){
            System.out.println(this.elem[i]+" ");
        }
        System.out.println();
    }

    @Override
    public void add(int data) {
        checkCapacity();
        this.elem[usedSize++]=data;
    }
    private void checkCapacity(){
        if(isFull()){
            elem= Arrays.copyOf(elem,elem.length*2);
        }
    }
    public boolean isFull(){
        return usedSize==elem.length;
    }

    @Override
    public void add(int pos, int data) {
        try{
            checkPosOnAdd(pos);
        }catch (PosIllegality e){
            e.printStackTrace();
            return;
        }
        checkCapacity();
        for(int i=usedSize-1;i>=pos;i--){
            elem[i+1]=elem[i];
        }
        elem[pos]=data;
        usedSize++;
    }
    private void checkPosOnAdd(int pos) throws PosIllegality{
        if(pos<0||pos>usedSize){
            System.out.println("不合法！");
            throw new PosIllegality("插入下标异常："+pos);
        }
    }

    @Override
    public boolean contains(int toFind) {
        if(isEmpty()){
            return false;
        }
        for(int i=0;i<usedSize;i++){
            if(elem[i]==toFind){
                return true;
            }
        }
        return false;
    }
    public boolean isEmpty(){
        return usedSize==0;
    }

    @Override
    public int indexOf(int toFind) {
        if(isEmpty()){
            return -1;
        }
        for(int i=0;i<usedSize;i++){
            if(elem[i]==toFind){
                return i;
            }
        }
        return -1;
    }
    public int get(int pos) throws MyArrayListEmpty{
        checkCapacity();
        if(isEmpty()){
            throw new MyArrayListEmpty("获取指定下标元素时"+"顺序表为空");
        }
        return elem[pos];
    }
    public void remove(int toRemove){
        int index=indexOf(toRemove);
        if(index==-1){
            System.out.println("没有这个数字！");
            return;
        }
        for(int i=index;i<usedSize-1;i++){
            elem[i]=elem[i+1];
        }
        usedSize--;
    }
    public int size(){
        return this.usedSize;
    }
    public void clear(){
        this.usedSize=0;
    }

    @Override
    public void set(int pos, int value) {
        checkPosOnAdd(pos);
        elem[pos]=value;
    }
}
